package cn.harry.cabinet.repository

import android.app.Application
import cn.harry.cabinet.database.AppDatabase
import cn.harry.cabinet.model.entity.Configuration
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

/**
 * 配置数据仓库
 */
class ConfigurationRepository(application: Application) : BaseRepository() {

	private val configurationDao = AppDatabase.getDatabase(application).configurationDao()

	suspend fun getAll(): List<Configuration> = withContext(Dispatchers.IO) {
		configurationDao.getAllConfigurations()
	}

	suspend fun getById(id: Long): Configuration? = withContext(Dispatchers.IO) {
		configurationDao.getConfigurationById(id)
	}

	suspend fun getByType(type: String): List<Configuration> = withContext(Dispatchers.IO) {
		configurationDao.getConfigurationsByType(type)
	}

	suspend fun getByTypeAndKey(type: String, key: String): Configuration? = withContext(Dispatchers.IO) {
		configurationDao.getConfigurationByTypeAndKey(type, key)
	}

	suspend fun create(configuration: Configuration): Configuration = withContext(Dispatchers.IO) {
		val id = configurationDao.insertConfiguration(configuration)
		configuration.copy(id = id)
	}

	suspend fun update(configuration: Configuration) = withContext(Dispatchers.IO) {
		configurationDao.updateConfiguration(configuration)
	}

	suspend fun delete(configuration: Configuration) = withContext(Dispatchers.IO) {
		configurationDao.deleteConfiguration(configuration)
	}
}

